package in.muton.edushare.jobs;

import in.muton.edushare.schedules.widgets.DateHelper;

import java.util.Date;
import java.util.List;

import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.query.SelectQuery;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.edushare.common.orm.CayenneORMInterface;
import com.edushare.common.vo.Poll;

public class PollUpdater implements EduShareJob {
	@SuppressWarnings("unchecked")
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		CayenneORMInterface ormIntf = new CayenneORMInterface();
		ormIntf.setDataContext(DataContext.createDataContext());
		SelectQuery selQ = new SelectQuery(Poll.class);
		List<Poll> pollList = ormIntf.getDataContext().performQuery(selQ);
		for (Poll p : pollList) {
			if (p.getStatus() == Poll.POLL_STATUS_POLLING) {
				if (DateHelper.before(p.getPollEndDate(), new Date())
						|| DateHelper.sameDay(p.getPollEndDate(), new Date())) {
					p.setStatus(Poll.POLL_STATUS_CLOSED);
				}
			}
			ormIntf.commitAllChanges();
		}
	}
}
